package com.copm.ifm.base.api.anno.log;

import com.alibaba.fastjson.JSON;
import com.copm.ifm.base.api.anno.log.annotation.LogAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author tp
 */
@Aspect
@Component
@Slf4j
public class SystemLogAspect {

    /**
     * 通过注解的方式加入切入点
     **/
    @Pointcut("@annotation(com.copm.ifm.base.api.anno.log.annotation.LogAnnotation)")
    public void logPointCut() {
        System.out.println("初始化注解切入点...");
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object method = point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        System.out.println("方法执行耗时:" + time);
        /**  做点其他事情,比如记录日志 **/
        try {
            saveSysLog(point, time);
        } catch (Exception e) {
            log.error("e={}", e);
        }
        return method;
    }

    /**
     * 记录日志
     **/
    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        if (logAnnotation != null) {
            //注解上的描述
            log.info("{}-{}", logAnnotation.title(), logAnnotation.action());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("请求{}.{}耗时{}毫秒", className, methodName, time);
        try {
            //请求的参数
            Object[] args = joinPoint.getArgs();
            String params = null;
            if (args.length != 0) {
                params = JSON.toJSONString(args);
            }
            log.info(params);
        } catch (Exception e) {
            log.error("e={}", e);
        }
    }
}
